package dao;

import classes.Market;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class MarketDAO {
	@SuppressWarnings("unused")
	private final Connection c;
	private final PreparedStatement qSelect, qInsert, qSelectAll, qDelete, qSelectMarket;
	
	public MarketDAO(Connection c) throws Exception {
		this.c = c;
		qInsert= c.prepareStatement("INSERT INTO market(idMarket, naziv, username, password) VALUES(null, ?,?,?)");
		qSelect= c.prepareStatement("SELECT naziv FROM Market WHERE username = ?");
		qSelectAll = c.prepareStatement("SELECT * FROM market");
		qDelete = c.prepareStatement("DELETE FROM market WHERE idMarket=?");
		qSelectMarket = c.prepareStatement("SELECT * FROM Market WHERE idMarket = ?");
	}
/**	
	public String nazivMarketa(String username){
		try{
			qSelect.setString(1, username);
			ResultSet rs = qSelect.executeQuery();
			String naziv = rs.getString(1);
			rs.close();
			return naziv;
		}
		catch (Exception e){
			return "Nema !!!";
		}
	}*/

	public int insertMarket(Market m) throws Exception {
		if (m==null)
			throw new Exception("Nije moguce dodati nepostojeci market!");
		qInsert.setString(1, m.getNaziv());
		qInsert.setString(2, m.getUsername());
		qInsert.setString(3, m.getPassword());
		try{
			int r= qInsert.executeUpdate();
			return r;
		}
		catch(Exception ex){
			throw new Exception("Greska kod dodavanja marketa!");
		}
	}
	
	public Market selectMarket(int id) throws Exception{
		qSelectMarket.setInt(1, id);
		ResultSet rs = qSelectMarket.executeQuery();
		if(rs.next()==false)
			throw new Exception("Vratio null");
		Market m = new Market();
		m.setIdMarket(rs.getInt("idMarket"));
		m.setNaziv(rs.getString("naziv"));
		m.setUsername(rs.getString("username"));
		m.setPassword(rs.getString("password"));
		return m;
	}
	
	
	public List<Market> selectSviMarketi() throws Exception{
		ResultSet rs = qSelectAll.executeQuery();
		List<Market> marketi = new ArrayList<Market>();
		while (rs.next()){
			Market m= new Market();
			m.setIdMarket(rs.getInt("idMarket"));
			m.setNaziv(rs.getString("naziv"));
			m.setUsername(rs.getString("username"));
			m.setPassword(rs.getString("password"));
			marketi.add(m);
		}
		return marketi;
	}

	public int deleteMarket(int id) throws Exception {
		qDelete.setInt(1, id);
		return qDelete.executeUpdate();
	}
}
